package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.config.CacheService;
import com.heima.user.service.UserRelationService;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class UserRelationServiceImpl implements UserRelationService {
    @Autowired
    CacheService cacheService;

    /**
     * 添加关注/取消关注
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //参数校验
        if (dto == null || dto.getAuthorApUserId() == null || dto.getOperation() < 0 || dto.getOperation() > 1) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前登录人的id
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //当前登录人的id
        Integer apUserId = apUser.getId();
        //被关注的文章作者对应的用户id
        Integer authorApUserId = dto.getAuthorApUserId();
        //执行关注
        if (dto.getOperation() == 0) {
            Double score = cacheService.zScore(UserRelationConstants.FOLLOW_LIST + apUserId, authorApUserId.toString());
            if (score != null) {
                CustException.cust("已关注,无需重复关注");
            }
            //将对方写入我的关注中
            cacheService.zAdd(UserRelationConstants.FOLLOW_LIST + apUserId, authorApUserId.toString(), System.currentTimeMillis());

            //将我写入对方粉丝中
            cacheService.zAdd(UserRelationConstants.FANS_LIST + authorApUserId, apUserId.toString(), System.currentTimeMillis());
        } else {
            //执行取消关注
            //在我的关注中取消对方
            cacheService.zRemove(UserRelationConstants.FOLLOW_LIST + apUserId, authorApUserId.toString());
            //在对方粉丝中取消我
            cacheService.zRemove(UserRelationConstants.FANS_LIST + authorApUserId, apUserId.toString());
        }

        return ResponseResult.okResult();
    }
}
